package com.defysoft.waukids.main;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class Main_SearchMember extends BaseActivity implements OnClickListener{
	Toolbar toolbar;
	TextView title;
	EditText editText;
	Button button;
	String email;

	public Sqlite_Connect sqlite_Connect;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	
	final int SEND_EMAIL = 1;
	private final int SUCCESS_DATA= 9;
	private final int FAIR_DATA = 10;
	
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.main_searchmember_activity);
		setToolbar();
		setStartData();
	}
	private void setToolbar() {
		toolbar = (Toolbar)findViewById(R.id.MAIN_SEARCHMEMBER_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
					finish();
			}
		});
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		title = (TextView)findViewById(R.id.MAIN_SEARCHMEMBER_TOOLBAR_TITLE);
		editText = (EditText)findViewById(R.id.MAIN_SEARCHMEMBER_EDITTEXT_EMAIL);
		button = (Button)findViewById(R.id.MAIN_SEARCHMEMBER_BUTTON_SENDEMAIL);
		button.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MAIN_SEARCHMEMBER_BUTTON_SENDEMAIL:
			email = editText.getText().toString();
			if (!isEmailValid(email)) {
				editText.setText("");
				editText.setHint("이메일 형식이 맞지 않습니다.");
				editText.setHintTextColor(Color.RED);
			} else {
				sendEmail();
			}
			break;

		}
	}
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SEND_EMAIL:
					sendEmailThread();
					break;
				}
			}
		});
		startDIal();
		firstThread.start();
	}
	
	protected void sendEmailThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, 
					"code=" + CODE_MAIN_SEARCHMEMBER_SEND_EMAIL + "&email="+email));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_DATA, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIR_DATA,  jsonObject.getString("message"));
			}
			
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where sendEmailThread()");
		}
	}
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_DATA:
				//임시비밀번호가 전송 되었습니다.(확인). 어플 종료.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			sendEmailSuccess();
			break;
		case FAIR_DATA:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_SearchMember", member.Email);
			break;

		}
	}
	
	boolean isEmailValid(CharSequence email){
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
		
	}
	// 메일전송 선택.
	private void sendEmail() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_SearchMember.this);
		builder.setMessage(
				"서비스 신청 시 제출한 E-mail로 임시 비밀번호를 받으시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("네",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startNetwork(SEND_EMAIL);
								dialog.cancel();
							}
						})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
	// 메일전송 어플종료.
	private void sendEmailSuccess() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_SearchMember.this);
		builder.setMessage(
				"임시 비밀번호가 전송 되었습니다. 확인 후 로그인 하세요.")
				.setCancelable(false)
				.setNegativeButton("예",
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						finish();
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
}
